package kinon.canteen.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.AbsoluteSizeSpan;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;

import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;

import java.util.ArrayList;

import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import kinon.canteen.R;
import kinon.canteen.adapter.ShopCartAdapter;
import kinon.canteen.adapter.viewpage.MyFragmentAdapter;
import kinon.canteen.application.Constant;
import kinon.canteen.bean.OrderTypeBean;
import kinon.canteen.bean.ShopCartBean;
import kinon.canteen.bean.UpCartBean;
import kinon.canteen.bean.base.BaseBean;
import kinon.canteen.fragment.goods.FoodFragment;
import kinon.canteen.network.HttpManage;
import kinon.canteen.network.http.CommonSubscriber;
import kinon.canteen.network.http.StrCallback;
import kinon.canteen.util.MyDecimalFormat;
import kinon.canteen.util.RxBus;
import kinon.canteen.util.RxUtil;
import kinon.canteen.util.ShardPManager;
import retrofit2.Call;
import retrofit2.Response;

/**
 * Created by lhqq on 2018-01-02.
 * 商品购买页面
 */

public class OrderFoodActivity extends BaseActivity implements View.OnClickListener{

    private ImageView img_back;
    private TextView tv_title;
    private RadioGroup rg_foodType;
    private ViewPager vp_food;
    private TextView tv_totalNum;
    private ImageView img_shopCar;
    private TextView tv_settlement;
    private TextView tv_totalPrice;

    private int goodType=0;
    private ArrayList<Fragment> fragmentList;
    private ArrayList<OrderTypeBean> typeList;
    private CompositeDisposable mCdisposable;
    Disposable dis;

    private int amount=0;
    private double price=0.0;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_orderfood_layout);
        initView();
    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    private void initView() {

        img_back= (ImageView) findViewById(R.id.img_back);
        tv_title= (TextView) findViewById(R.id.tv_title);
        rg_foodType= (RadioGroup) findViewById(R.id.rg_foodType);
        vp_food= (ViewPager) findViewById(R.id.vp_food);
        tv_totalNum= (TextView) findViewById(R.id.tv_totalNum);
        img_shopCar= (ImageView) findViewById(R.id.img_shopCar);
        tv_settlement= (TextView) findViewById(R.id.tv_settlement);
        tv_totalPrice= (TextView) findViewById(R.id.tv_totalPrice);
        goodType=getIntent().getIntExtra("goodType",0);

        mCdisposable=new CompositeDisposable();
        fragmentList=new ArrayList<>();
        typeList=new ArrayList<>();
        img_back.setVisibility(View.VISIBLE);

        if(goodType==0){
            tv_title.setText("晚餐");
        }else{
            tv_title.setText("超市购");
        }
        addListener();

        getCategories();
        upDataShow();
        getCart();
    }

    private void upDataShow(){
        RxBus.getDefault().toFlowable(UpCartBean.class)
        .subscribeOn(Schedulers.io())
        .compose(RxUtil.<UpCartBean>rxSchedulerHelper())
        .subscribeWith(new CommonSubscriber<UpCartBean>() {
            @Override
            public void onNext(UpCartBean upCartBean) {
                price+=upCartBean.getTotal();
                amount+=upCartBean.getAmount();
                String strPrice=String.valueOf(price);
                tv_totalNum.setText("共计:"+amount+"件");
                tv_totalPrice.setText(""+(strPrice.length()>8?
                        MyDecimalFormat.dFormat(price):strPrice));
//                tv_totalNum.setText("共计:"+upCartBean.getAmount()+"件");
//                tv_totalPrice.setText(""+upCartBean.getTotal());
            }

            @Override
            public void onFail(Throwable t, int code, String msg) {

            }
        });

    }

    private void getCategories(){
         dis= HttpManage.getInstance()
                .getCategories(ShardPManager.getInstance().getToken(),goodType)
                .compose(RxUtil.<BaseBean<ArrayList<OrderTypeBean>>>rxSchedulerHelper())
                .compose(RxUtil.<ArrayList<OrderTypeBean>>handleResult())
                .subscribeWith(new CommonSubscriber<ArrayList<OrderTypeBean>>() {
                    @Override
                    public void onNext(ArrayList<OrderTypeBean> list) {
                        Log.e("lh", "onNext== ");
                        typeList.addAll(list);
                        showType(typeList);
                    }

                    @Override
                    public void onFail(Throwable t, int code, String msg) {

                    }
                });
        mCdisposable.add(dis);
//        dis.dispose();


    }

    private void getCart(){
        Call<String> call=HttpManage.getInstance()
                .getCart(ShardPManager.getInstance().getToken());
        call.enqueue(new StrCallback<String>() {
            @Override
            public void onSuccess(Response<String> response, String data) {
                Gson gson=new Gson();
                ShopCartBean shaoCartBean=gson.fromJson(data,ShopCartBean.class);
                for(ShopCartBean.Carts c:shaoCartBean.getShoppingcarts()){
                    if(c.getType()==goodType){
                        amount+=c.getAmount();
                        price+=c.getAmount()*c.getPrice();
                    }
                }
                String strPrice=String.valueOf(price);
                tv_totalNum.setText("共计:"+amount+"件");
                tv_totalPrice.setText(""+(strPrice.length()>8?
                        MyDecimalFormat.dFormat(price):strPrice));
            }

            @Override
            public void onError(int code, String error) {
               mToast(error);
            }
        });
    }


    private void showType(ArrayList<OrderTypeBean> list){

        rg_foodType.removeAllViews();
        RadioGroup.LayoutParams lp=new RadioGroup.LayoutParams
                (RadioGroup.LayoutParams.MATCH_PARENT,
                RadioGroup.LayoutParams.MATCH_PARENT, 1);
        lp.gravity = Gravity.CENTER;
        for(int i=0;i<typeList.size();i++){
            Log.e("lh", "i== "+i);
            RadioButton rb=new RadioButton(OrderFoodActivity.this);
            rb.setId(i);
            rb.setWidth(RadioGroup.LayoutParams.MATCH_PARENT);
            rb.setHeight(RadioGroup.LayoutParams.WRAP_CONTENT);
            rb.setGravity(Gravity.CENTER);
            rb.setBackground(getResources().getDrawable(R.drawable.img_select_foodtype));
            rb.setButtonDrawable(android.R.color.transparent);
            rb.setTextSize(15);
            rb.setTextColor(getResources().getColor(R.color.color_select_foodtype));
            if(typeList.get(i).getLim()>0){
                String rbStr=typeList.get(i).getName()
                        +"\n(限购:"+typeList.get(i).getLim()+")";
                SpannableString textAttr=new SpannableString(rbStr);
                textAttr.setSpan(new AbsoluteSizeSpan(12,true),
                        typeList.get(i).getName().length(),rbStr.length(),
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                rb.setText(textAttr);
            }else{
                rb.setText(typeList.get(i).getName());
            }
            rg_foodType.addView(rb,lp);

            //设置fragment
            showFragment(typeList,i);

        }
        if(typeList.size()>0){
            ((RadioButton)rg_foodType.getChildAt(0)).setChecked(true);
        }
        Log.e("lh", "size== "+typeList.size());

        MyFragmentAdapter adapter=new MyFragmentAdapter
                (getSupportFragmentManager(),fragmentList);
        vp_food.setAdapter(adapter);
//        dis.dispose();

    }

    private void showFragment(ArrayList<OrderTypeBean> typeList,int i){
        FoodFragment foodFragment=new FoodFragment();
        Bundle bundle=new Bundle();
        bundle.putInt("catid",typeList.get(i).getId());
        bundle.putInt("goodType",goodType);
        foodFragment.setArguments(bundle);
        fragmentList.add(foodFragment);
    }

    private void addListener() {
        img_back.setOnClickListener(this);
        img_shopCar.setOnClickListener(this);
        tv_settlement.setOnClickListener(this);
        rg_foodType.setOnCheckedChangeListener(checkListener);
        vp_food.setOnPageChangeListener(pageListener);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.img_back:
                finish();
                break;
            case R.id.img_shopCar:
                Intent cartIntent=new Intent(OrderFoodActivity.this,MainActivity.class);
                setResult(Constant.PAY_CART_ACTIVITY);
                finish();

                break;
            case R.id.tv_settlement:
                Intent intent=new Intent(OrderFoodActivity.this,PaymentActivity.class);
                intent.putExtra("mGoodType",goodType);
                startActivity(intent);
                finish();

                break;
        }
    }

    private RadioGroup.OnCheckedChangeListener checkListener=new RadioGroup.OnCheckedChangeListener(){
        @Override
        public void onCheckedChanged(RadioGroup radioGroup, int i) {
            Log.e("lh", "onCheckedChanged== "+i );
            vp_food.setCurrentItem(i);
        }
    };

    private ViewPager.OnPageChangeListener pageListener=new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }
        @Override
        public void onPageSelected(int position) {
            Log.e("lh", "position== "+position );
            ((RadioButton)rg_foodType.getChildAt(position)).setChecked(true);
        }
        @Override
        public void onPageScrollStateChanged(int state) {
        }
    };



    @Override
    protected void onDestroy() {
        super.onDestroy();
        typeList.clear();
        mCdisposable.dispose();
//        dis.dispose();
        mCdisposable.clear();

        checkListener=null;


    }


}
